#include "mainwindow.h"
#include "ui_mainwindow.h"

QTcpServer server;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->statusBar->showMessage("Zainicjalizowano okno.");

    QHostAddress addr = QHostAddress::Any;
    server.listen(addr, 1337);
    this->connect(&server, SIGNAL(newConnection()), this, SLOT(processPendingDatagrams()));
    trayIconMenu = new QMenu();
   // quit_action = new QAction( "Exit", tray );
   // connect( quit_action, SIGNAL(triggered()), this, SLOT(bringIt()) );
    tray = new QSystemTrayIcon(this);
    tray->setContextMenu(trayIconMenu);
    tray->show();
    tray->setToolTip("Requests");
    tray->setIcon(QIcon(":/img/layer1-7.png"));
    this->connect(tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(bringIt()));
    this->connect(tray, SIGNAL(messageClicked()), this, SLOT(bringIt()));
    //  tray->setContextMenu(trayIconMenu);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::bringIt()
{
    this->activateWindow();
}

void MainWindow::processPendingDatagrams()
{
     ui->statusBar->showMessage("Polaczenie.");
    //sock = new QTcpSocket;
    //sock = server.nextPendingConnection();
    //QString str;
    //QTcpSocket.read ( str, 255);


//    QByteArray block;
    //QDataStream out(&block, QIODevice::ReadOnly);
    //out.setVersion(QDataStream::Qt_4_0);
    //out << (quint16)0;
    //out << fortunes.at(qrand() % fortunes.size());
    //out.device()->seek(0);
    //out << (quint16)(block.size() - sizeof(quint16));

         QTcpSocket* socket = server.nextPendingConnection();
//    connect(clientConnection, SIGNAL(disconnected()),
//            clientConnection, SLOT(deleteLater()));
//         if (socket->canReadLine()) {
              ui->statusBar->showMessage("Reading.");
              if (socket->waitForReadyRead (5000) == false) { return; }

//    block = clientConnection->readAll();
//    clientConnection->disconnectFromHost();
             QString tokens = QString(socket->readAll());
             QString getText = this->ui->plainTextEdit->toPlainText();
             this->ui->plainTextEdit->setPlainText(getText.append(tokens));
             socket->disconnectFromHost();
             tray->showMessage("Nowy request", tokens);
             ui->statusBar->showMessage("Ready.");

//    }
}

void MainWindow::on_commandLinkButton_clicked()
{
    this->ui->plainTextEdit->setPlainText("");
}
